package com.ycb.bookserver.controller.user;

import com.book.constant.JWTClaimsConstant;
import com.book.context.BaseContext;
import com.book.properties.JWTProperties;
import com.book.result.Result;
import com.book.utils.JWTUtils;
import com.ycb.book.dto.UserDTO;
import com.ycb.book.dto.UserLoginDTO;

import com.ycb.book.entity.User;

import com.ycb.book.vo.UserLoginVO;
import com.ycb.book.vo.UserReportVO;
import com.ycb.bookserver.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private JWTProperties jwtProperties;
    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/user/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("微信用户登录：{}", userLoginDTO.getCode());
        User user = userService.login(userLoginDTO);
        Map<String, Object> Claims = new HashMap<>();
        Claims.put(JWTClaimsConstant.USER_ID, user.getId());
        String jwt = JWTUtils.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), Claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(jwt).build();
        return Result.success(userLoginVO);
    }
    @GetMapping("/user/getUser/{idNumber}")
    public Result<UserReportVO> getUser(@PathVariable String idNumber){
        log.info("获取用户详细信息");
        UserReportVO userReportVO=userService.getUser(idNumber);
        return Result.success(userReportVO);
    }

    @PostMapping("/user/add")
    public Result add(@RequestBody UserDTO userDTO){
        log.info("注册新用户");
        User user=new User();
        BeanUtils.copyProperties(userDTO, user);
        userService.add(user);
        return Result.success();
    }
    @DeleteMapping("/user/delete/{id}")
    public Result delete(@PathVariable Integer id){
        log.info("删除用户：{}", BaseContext.getCurrentId());
        userService.delete(id);
        return Result.success();
    }


    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }



}
